package com.xyy.saas.payment.adpater.yop;

import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.util.JSONUtils;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.account.AccountClient;
import com.yeepay.yop.sdk.service.account.AccountClientBuilder;
import com.yeepay.yop.sdk.service.account.model.BalanceQueryAccountInfoRespDTOResult;
import com.yeepay.yop.sdk.service.account.request.*;
import com.yeepay.yop.sdk.service.account.response.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class YopBalanceQuery {
// 该Client线程安全，请使用单例模式，多次请求共用
private final AccountClient api = AccountClientBuilder.builder().build();

  /**
  * 资金账户余额查询
  */
  public BalanceQueryAccountInfoRespDTOResult balanceQuery(BalanceQueryRequest param) throws PaymentException {
    log.info("YopBalanceQuery#balanceQuery param:{}", JSONUtils.toJSON(param));

    try {
        BalanceQueryResponse response = api.balanceQuery(param);
        log.info("YopBalanceQuery#balanceQuery request:{} response:{}", JSONUtils.toJSON(param), JSONUtils.toJSON(response));
        BalanceQueryAccountInfoRespDTOResult result = response.getResult();

        if(!Constants.YOP_SUCCESS_CODE.equals(result.getReturnCode())) {
            throw new PaymentException(result.getReturnCode(), result.getReturnMsg());
        }

        return result;
    }
    catch(Exception ex) {
        log.error("YopBalanceQuery#balanceQuery error, param=" + JSONUtils.toJSON(param) + ", errorMsg=" + ex.getMessage() ,ex);

        if(ex instanceof PaymentException) {
            throw ex;
        }
        else if(ex instanceof YopClientException) {
            throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR.getCode(), ex.getMessage());
        }

        throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR);
    }
  }
}